const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const path = require('path');
const { testConnection } = require('./database');
const scheduler = require('./scheduler');

// 导入路由
const hospitalsRouter = require('./routes/hospitals');
const departmentsRouter = require('./routes/departments');
const doctorsRouter = require('./routes/doctors');
const appointmentPoolsRouter = require('./routes/appointment-pools');
const appointmentsRouter = require('./routes/appointments');
const schedulerRouter = require('./routes/scheduler');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件配置
app.use(cors()); // 允许跨域请求
app.use(bodyParser.json()); // 解析JSON请求体
app.use(bodyParser.urlencoded({ extended: true })); // 解析URL编码的请求体

// 静态文件服务
app.use('/static', express.static(path.join(__dirname, 'public')));

// 请求日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
  next();
});

// 健康检查接口
app.get('/health', (req, res) => {
  res.json({
    success: true,
    message: '服务运行正常',
    timestamp: new Date().toISOString()
  });
});

// API路由
app.use('/api/hospitals', hospitalsRouter);
app.use('/api/departments', departmentsRouter);
app.use('/api/doctors', doctorsRouter);
app.use('/api/appointment-pools', appointmentPoolsRouter);
app.use('/api/appointments', appointmentsRouter);
app.use('/api/scheduler', schedulerRouter);

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    message: '接口不存在'
  });
});

// 错误处理中间件
app.use((error, req, res, next) => {
  console.error('服务器错误:', error);
  res.status(500).json({
    success: false,
    message: '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? error.message : '服务器错误'
  });
});

// 启动服务器
app.listen(PORT, async () => {
  console.log(`🚀 服务器启动成功，端口: ${PORT}`);
  console.log(`📖 API文档: http://localhost:${PORT}/api-docs`);
  
  // 测试数据库连接
  await testConnection();
  
  // 启动定时任务
  scheduler.start();
});

// 优雅关闭
process.on('SIGINT', () => {
  console.log('\n🛑 收到退出信号，正在关闭服务器...');
  scheduler.stop();
  process.exit(0);
});

process.on('SIGTERM', () => {
  console.log('\n🛑 收到终止信号，正在关闭服务器...');
  scheduler.stop();
  process.exit(0);
});

module.exports = app;
